package org.mozhu.mboot.core.web.freemarker;

import freemarker.template.SimpleScalar;
import freemarker.template.TemplateMethodModelEx;
import freemarker.template.TemplateModelException;
import org.mozhu.mboot.core.web.RequestContextHolder;
import org.springframework.web.servlet.support.BindStatus;
import org.springframework.web.servlet.support.RequestContext;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@SuppressWarnings("rawtypes")
public class FormHasFieldErrorMethod implements TemplateMethodModelEx {
    @Override
    public Object exec(List arguments) throws TemplateModelException {
        if (arguments.size() == 1) {
            return hasFieldError(getAsString(arguments.get(0)));
        }
        return new TemplateModelException("at least one argument");
    }

    private String getAsString(Object object) {
        if (object instanceof SimpleScalar) {
            return ((SimpleScalar) object).getAsString();
        }
        return (String) object;
    }

    public boolean hasFieldError(String path) {
        HttpServletRequest request = RequestContextHolder.getRequest();
        HttpServletResponse response = RequestContextHolder.getResponse();
        RequestContext requestContext = new RequestContext(request, response);
        BindStatus bindStatus = requestContext.getBindStatus(path);
        return bindStatus.getErrors().hasFieldErrors();
    }
}
